import { useState } from 'react';
import styles from './index.module.less';
import HeaderNav from '@/components/header-nav';
import { Form, ImageUploader, Button, Space } from 'antd-mobile';
import { handleImageUpload } from '@/utils/upload';
const { postEditChatImage } = $globalServicer('chat')
import { useSearchParams } from 'react-router-dom';
import { showErrorToast } from '@/utils/customToast';
const ChatImage = () => {
  const customNavigate = $globalNavigate()
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const [params] = useSearchParams();
  const id = params.get('id');
  
  // 跟踪每个上传区域的上传失败状态
  const [imageUploadFailed, setImageUploadFailed] = useState(false);
  const [coverUploadFailed, setCoverUploadFailed] = useState(false);
  const [roleCoverUploadFailed, setRoleCoverUploadFailed] = useState(false);
  
  // 跟踪错误信息
  const [imageError, setImageError] = useState('');
  const [coverError, setCoverError] = useState('');
  const [roleCoverError, setRoleCoverError] = useState('');
  
  // 跟踪是否在提交时显示错误
  const [showSubmitErrors, setShowSubmitErrors] = useState(false);

  // 验证图片是否已上传
  const isImageUploaded = (imageField) => {
    if (!imageField || !Array.isArray(imageField) || imageField.length === 0) {
      return false;
    }
    const image = imageField[0];
    
    // 检查是否有有效的URL或path
    const hasUrl = !!(image.url || image.path);
    return hasUrl;
  };

  // 检查是否有图片上传失败（基于状态判断）
  const hasImageUploadError = (fieldName) => {
    switch (fieldName) {
      case 'image':
        return imageUploadFailed;
      case 'cover':
        return coverUploadFailed;
      case 'role_cover':
        return roleCoverUploadFailed;
      default:
        return false;
    }
  };  
  const onFinish = (values) => {
    if (submitting) return; // 如果正在提交，直接返回
    
    console.log(`======values`, values)
    
    // 检查是否有上传失败的情况，如果有则显示错误信息
    if (imageUploadFailed || coverUploadFailed || roleCoverUploadFailed) {
      // 显示红色错误文字
      setShowSubmitErrors(true);
      
      // 显示弹窗提示
      if (imageUploadFailed) {
        showErrorToast(imageError || '图片上传失败，请调整图片大小');
      } else if (coverUploadFailed) {
        showErrorToast(coverError || '图片上传失败，请调整图片大小');
      } else if (roleCoverUploadFailed) {
        showErrorToast(roleCoverError || '图片上传失败，请调整图片大小');
      }
      return;
    }
    
    // 清除提交错误显示
    setShowSubmitErrors(false);
    
    // 构建提交数据
    const submitData = { id };
    
    // 添加背景图
    if (values.image?.[0]?.url) {
      submitData.image = values.image[0].url;
    }
    
    // 添加智能体头像
    if (values.cover?.[0]?.url) {
      submitData.cover = values.cover[0].url;
    }
    
    // 添加人设头像
    if (values.role_cover?.[0]?.url) {
      submitData.role_cover = values.role_cover[0].url;
    }
    
    // 如果没有任何图片，直接返回
    if (!submitData.image && !submitData.cover && !submitData.role_cover) {
      customNavigate(-1)
      return
    }
    
    setSubmitting(true);
    postEditChatImage(submitData).then(() => {
      setSubmitting(false);
      customNavigate(-1)
    }).catch(() => {
      setSubmitting(false);
    })
  }
  return (
    <div className={styles.chatBackImage}>
      <div className={styles.chatBackImageHeader}>
        <HeaderNav backArrow={true} title="聊天设置"></HeaderNav>
      </div>
      <div className={styles.chatBackImageContent}>
        <Form form={form}
          onFinish={onFinish}
          footer={
            <div className={styles.footer}>
              <Button className={styles.submitButton}
                type='submit'
                loading={submitting}
                disabled={submitting}
              >{submitting ? '提交中...' : '完成'}</Button>
            </div>
          }
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            {/* 背景图上传 */}
            <div className={styles.uploadSection}>
              <div className={styles.sectionTitle}>聊天背景</div>
              <div className={styles.avatarSection}>
                <Form.Item name="image">
                  <div>
                    <div className={styles.avatarUpload}>
                      <ImageUploader
                        style={{ '--cell-size': '120px' }}
                        className={styles.uploadWrapper}
                        upload={async (file) => {
                          try {
                            setImageUploadFailed(false); // 清除上传失败状态
                            setImageError(''); // 清除错误信息
                            const result = await handleImageUpload(file);
                            return result;
                          } catch (error) {
                            if (error.message === '图片大小超过2MB限制') {
                              setImageUploadFailed(true); // 标记为文件大小超限导致的上传失败
                              setImageError('图片上传失败，请调整图片大小'); // 设置错误信息
                            } else {
                              setImageUploadFailed(true); // 标记为其他原因导致的上传失败
                              setImageError('图片上传失败，请重试'); // 设置错误信息
                            }
                            throw error;
                          }
                        }}
                        maxCount={1}
                        onChange={(fileList) => {
                          try {
                            form.setFieldValue('image', fileList);
                            // 清除验证错误提示
                            form.setFields([{
                              name: 'image',
                              errors: []
                            }]);
                            // 清除提交错误显示
                            setShowSubmitErrors(false);
                          } catch (error) {
                            console.warn('Form not ready for image update:', error);
                          }
                        }}
                        onDelete={() => {
                          setImageUploadFailed(false); // 删除图片时清除上传失败状态
                          setImageError(''); // 删除图片时清除错误信息
                          return { beforeDelete: () => true };
                        }}
                      >
                        <span className="material-icons-outlined add-a-photo-icon">add_a_photo</span>
                      </ImageUploader>
                    </div>
                    <p className={styles.uploadText}>上传头像(仅支持2MB大小以下图片上传)</p>
                    {showSubmitErrors && imageUploadFailed && <p className={styles.errorText}>{imageError || '图片上传失败，请调整图片大小'}</p>}
                  </div>
                </Form.Item>
              </div>
            </div>

            {/* 智能体头像上传 */}
            <div className={styles.uploadSection}>
              <div className={styles.sectionTitle}>智能体头像</div>
              <div className={styles.avatarSection}>
                <Form.Item name="cover">
                  <div>
                    <div className={styles.avatarUpload}>
                      <ImageUploader
                        style={{ '--cell-size': '120px' }}
                        className={styles.uploadWrapper}
                        upload={async (file) => {
                          try {
                            setCoverUploadFailed(false); // 清除上传失败状态
                            setCoverError(''); // 清除错误信息
                            const result = await handleImageUpload(file);
                            return result;
                          } catch (error) {
                            if (error.message === '图片大小超过2MB限制') {
                              setCoverUploadFailed(true); // 标记为文件大小超限导致的上传失败
                              setCoverError('图片上传失败，请调整图片大小'); // 设置错误信息
                            } else {
                              setCoverUploadFailed(true); // 标记为其他原因导致的上传失败
                              setCoverError('图片上传失败，请重试'); // 设置错误信息
                            }
                            throw error;
                          }
                        }}
                        maxCount={1}
                        onChange={(fileList) => {
                          try {
                            form.setFieldValue('cover', fileList);
                            // 清除验证错误提示
                            form.setFields([{
                              name: 'cover',
                              errors: []
                            }]);
                            // 清除提交错误显示
                            setShowSubmitErrors(false);
                          } catch (error) {
                            console.warn('Form not ready for cover update:', error);
                          }
                        }}
                        onDelete={() => {
                          setCoverUploadFailed(false); // 删除图片时清除上传失败状态
                          setCoverError(''); // 删除图片时清除错误信息
                          return { beforeDelete: () => true };
                        }}
                      >
                        <span className="material-icons-outlined add-a-photo-icon">add_a_photo</span>
                      </ImageUploader>
                    </div>
                    <p className={styles.uploadText}>上传头像(仅支持2MB大小以下图片上传)</p>
                    {showSubmitErrors && coverUploadFailed && <p className={styles.errorText}>{coverError || '图片上传失败，请调整图片大小'}</p>}
                  </div>
                </Form.Item>
              </div>
            </div>

            {/* 人设头像上传 */}
            <div className={styles.uploadSection}>
              <div className={styles.sectionTitle}>人设头像</div>
              <div className={styles.avatarSection}>
                <Form.Item name="role_cover">
                  <div>
                    <div className={styles.avatarUpload}>
                      <ImageUploader
                        style={{ '--cell-size': '120px' }}
                        className={styles.uploadWrapper}
                        upload={async (file) => {
                          try {
                            setRoleCoverUploadFailed(false); // 清除上传失败状态
                            setRoleCoverError(''); // 清除错误信息
                            const result = await handleImageUpload(file);
                            return result;
                          } catch (error) {
                            if (error.message === '图片大小超过2MB限制') {
                              setRoleCoverUploadFailed(true); // 标记为文件大小超限导致的上传失败
                              setRoleCoverError('图片上传失败，请调整图片大小'); // 设置错误信息
                            } else {
                              setRoleCoverUploadFailed(true); // 标记为其他原因导致的上传失败
                              setRoleCoverError('图片上传失败，请重试'); // 设置错误信息
                            }
                            throw error;
                          }
                        }}
                        maxCount={1}
                        onChange={(fileList) => {
                          try {
                            form.setFieldValue('role_cover', fileList);
                            // 清除验证错误提示
                            form.setFields([{
                              name: 'role_cover',
                              errors: []
                            }]);
                            // 清除提交错误显示
                            setShowSubmitErrors(false);
                          } catch (error) {
                            console.warn('Form not ready for role_cover update:', error);
                          }
                        }}
                        onDelete={() => {
                          setRoleCoverUploadFailed(false); // 删除图片时清除上传失败状态
                          setRoleCoverError(''); // 删除图片时清除错误信息
                          return { beforeDelete: () => true };
                        }}
                      >
                        <span className="material-icons-outlined add-a-photo-icon">add_a_photo</span>
                      </ImageUploader>
                    </div>
                    <p className={styles.uploadText}>上传头像(仅支持2MB大小以下图片上传)</p>
                    {showSubmitErrors && roleCoverUploadFailed && <p className={styles.errorText}>{roleCoverError || '图片上传失败，请调整图片大小'}</p>}
                  </div>
                </Form.Item>
              </div>
            </div>
          </Space>
        </Form>
      </div>
    </div>
  )
}

export default ChatImage;